<?php defined('SYSPATH') OR die('No direct script access.');

class Stourweb_View extends Class_View {
    //定义视图缓存目录
    public $_view_cache_dir = 'v5';

    /**引用文件
     * @param string 引入文件名
     * */
    public static function template($file)
    {
        if (file_exists(APPPATH . '/views/' . $GLOBALS['cfg_templet'] . '/' . $file . '.php'))
        {
            $tpl = $GLOBALS['cfg_templet'] . '/' . $file;
        }
        elseif (file_exists(BASEPATH . $GLOBALS['cfg_user_templet_dir'] . $file . '.php'))
        {
            $tpl = $GLOBALS['cfg_user_templet_dir'] . $file;
        }
        else
        {
            $tpl = 'default/' . $file;
        }
        echo Stourweb_View::factory($tpl, self::$_user_data);
    }

    public function capture($kohana_view_filename, array $kohana_view_data)
    {

        self::$_user_data = $kohana_view_data + self::$_global_data;
        // Import the view variables to local namespace
        extract($kohana_view_data, EXTR_SKIP);

        if (Stourweb_View::$_global_data)
        {
            // Import the global view variables to local namespace
            extract(Stourweb_View::$_global_data, EXTR_SKIP | EXTR_REFS);
        }


        // Capture the view output
        ob_start();

        try
        {
            //检测缓存目录
            $tpl_cache_dir = CACHE_DIR . $this->_view_cache_dir.'/tplcache/';
            if(!file_exists($tpl_cache_dir))
            {
                mkdir($tpl_cache_dir,0777,true);
            }

            //如果使用的是视图解析
            if ($kohana_view_filename !== NULL)
            {
                $to = $tpl_cache_dir . $this->_templet . '.php';
                $isfileto = is_file($to);
                if (!$isfileto || filemtime($kohana_view_filename) > filemtime($to) || (filesize($to) == 0 && filesize($kohana_view_filename) > 0) || DEVELOPMENT_MODE == 1)
                {
                    $file_content = self::get_file($kohana_view_filename);
                    $new_content = self::compile_template($file_content, $this->_data);
                    //$new_content = self::compress_html($new_content);
                    self::write_file($to, $new_content);//写缓存文件.
                }
                include($to);
            }
            else if ($this->_innertext !== NULL)
            {
                $to = $tpl_cache_dir . $this->_innertex_name . '.php';
                $new_content = self::compile_template($this->_innertext, $this->_data);
                //$new_content = self::compress_html($new_content);
                if (is_file($to))
                {
                    $org_content = self::get_file($to);//原来缓存文件大小
                    //如果内容不等,则写缓存
                    if (strlen($new_content) !== $org_content)
                    {
                        self::write_file($to, $new_content);//写缓存文件.
                    }
                }
                else
                {
                    self::write_file($to, $new_content);//写缓存文件.
                }
                include($to);

            }


            // Load the view within the current scope

        } catch (Exception $e)
        {
            // Delete the output buffer
            ob_end_clean();

            // Re-throw the exception
            throw $e;
        }

        // Get the captured output and close the buffer
        return ob_get_clean();
    }

    /**
     * 解析ST标签
     * @param string $op 操作类
     * @param string $data 参数
     * @param string $html 匹配到的所有的HTML代码
     */
    public static function st_tag_start($op, $data, $kohana_view)
    {
        preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);

        $params = array();//标签参数

        foreach ($matches as $v)
        {

            $params[$v[1]] = $v[2];
        }

        $str = '';

        $return = isset($params['return']) && trim($params['return']) ? trim($params['return']) : 'data'; //默认返回数组
        $action = $params['action'];

        //  if (!isset($action) || empty($action)) return false;//操作方法

        $viewpath = str_replace('\\', '/', dirname($kohana_view));//视图文件目录

        $hastagfile = 0;//是否有标签文件.

        $includestr = '';

        //第一步从用户视图目录查看是否有标签文件存在
        if (file_exists($viewpath . '/taglib/' . $op . EXT))
        {
            $includestr = $viewpath . '/taglib/' . $op . EXT;
            $hastagfile = 1;

        }
        //第二步从项目标签目录查看是否存在标签文件
        elseif (file_exists(Kohana::find_file('classes', 'taglib/' . $op)))
        {
            $hastagfile = 1;
        }
        //第三步从项目定义公共标签库判断是否存在标签文件
        elseif (file_exists(TAGPATH . $op . EXT))
        {
            $pub_tag_path = str_replace('\\', '/', TAGPATH);
            $includestr = $pub_tag_path . $op . EXT;
            $hastagfile = 1;

        }
        //如果标签文件存在,则进行解析标签

        if ($hastagfile)
        {
            $is_installed = true;
            if ($includestr)
            {
                require_once $includestr;
                $includestr = 'require_once ("' . $includestr . '");';
            }
            $reflect = new ReflectionClass('Taglib_' . ucfirst($op));
            if ($reflect->hasMethod('right'))
            {
                $is_installed = $reflect->getMethod('right')->invoke($reflect->newInstance());
            }
            if ($is_installed)
            {
                $str .= $includestr;
                $str .= '$' . $op . '_tag = new Taglib_' . ucfirst($op) . '();if (method_exists($' . $op . '_tag, \'' . $action . '\')) {';
                $str .= '$' . $return . ' = $' . $op . '_tag->' . $action . '(' . self::arr_to_html($params) . ');';
                $str .= '}';
            }
        }
        return "<?php " . $str . "?" . ">";
    }

    public static function compress_html($string)
    {
        $string = str_replace("\n", '', $string); //清除换行符
        $string = str_replace("\t", '', $string); //清除制表符
        $string = preg_replace("~>\s+<~", "><", preg_replace("~>\s+\r\n~", ">", $string));
        return $string;


    }


}

